package SceretKey;

import java.security.SecureRandom;

/**
 * 生成离线码密钥
 * @author xiexiaojin
 * @date 2025-07-17 15:44
 */
public class GenerateLxmKey {
    public static void main(String[] args) {
        // 生成离线码的SM4密钥
        String lxm_sm4Key = generateHexKey();
        System.out.println("离线码的SM4密钥: " + lxm_sm4Key);

        // 生成离线码的SM3密钥(注：CST密钥和JRHX密钥都是这个方法生成，需要给第三方的是CST密钥)
        String lxm_sm3Key = generateSM3KeyForLxm(48);
        System.out.println("生成离线码的SM3密钥: " + lxm_sm3Key);
        String x="510000000";
    }

    /**
     * 生成十六进制编码的SM4密钥
     * @return 十六进制编码的密钥字符串
     */
    public static String generateHexKey() {
        byte[] key = generateRandomKey();
        StringBuilder hexString = new StringBuilder();
        for (byte b : key) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 生成随机SM4密钥（字节数组）
     * @return 16字节的随机密钥
     */
    public static byte[] generateRandomKey() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] key = new byte[8]; // SM4需要128位密钥
        secureRandom.nextBytes(key);
        return key;
    }

    /*
     * 生成离线码的SM3密钥
     */
    public static String generateSM3KeyForLxm(int length) {
        SecureRandom secureRandom = new SecureRandom();
        StringBuilder keyBuilder = new StringBuilder();
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        // 生成50个字符的密钥，与配置文件中的格式一致
        for (int i = 0; i < length; i++) {
            int index = secureRandom.nextInt(chars.length());
            keyBuilder.append(chars.charAt(index));
        }

        return keyBuilder.toString();
    }
}
